#include "db.h"

DB::DB(QObject *parent) : QObject(parent)
{
    m_db=QSqlDatabase::addDatabase("QSQLITE");
}

DB &DB::getinstance()
{
    static DB instance;
    return instance;
}

DB::~DB()
{
    m_db.close();
}

void DB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("C://QT_project//TcpServer//cloud.db");
    if(m_db.open())
    {
        QSqlQuery query;
        //.schema userInfo 查询表的结构
        query.exec("select * from userInfo;");
        while(query.next())
        {
            QString data=QString("%1,%2,%3").
                    arg(query.value(0).toString()).
                    arg(query.value(1).toString()).
                    arg(query.value(2).toString());
            qDebug()<<data;
        }

    }
    else
    {
        QMessageBox::critical(NULL,"打开数据库","打开数据库失败");
    }
}

bool DB::handleRegis(char *name, char *pwd)
{
    if(name==NULL&&pwd==NULL)
        return false;
    QString data=QString("insert into userInfo(name,pwd) values(\'%1\',\'%2\')").arg(name).arg(pwd);
    QSqlQuery query;
    return query.exec(data);
}

bool DB::handleLogin(char *name, char *pwd)
{
    if(name==NULL&&pwd==NULL)
        return false;
    QString data=QString("select * from userInfo where name = \'%1\'").arg(name);
    qDebug()<<data;
    QSqlQuery query;
    query.exec(data);
    int flag = 0;
    while(query.next())
    {
        QString ans_name = query.value(1).toString();
        QString ans_pwd = query.value(2).toString();
        int status = query.value(3).toInt();
        flag=1;
        if(strcmp(ans_pwd.toStdString().c_str(),pwd))
        {
            return false;
        }
        if(status==1)
        {
            return false;
        }

    }
    if(flag==0)
    {
        return false;
    }
    data=QString("update userInfo set onlint = 1 where name = \'%1\'").arg(name);
    query.exec(data);
    return true;
}

//用户下线数据库操作
bool DB::handleoffline(const char *name)
{
    if(name==NULL)
        return false;
    QString data=QString("update userInfo set onlint = 0 where name = \'%1\'").arg(name);
    qDebug()<<data;
    QSqlQuery query;
    return query.exec(data);
}

QStringList DB::handleAllUser()
{
    QString data=QString("select name from userInfo where onlint = 1");
    qDebug()<<data;
    QSqlQuery query;
    query.exec(data);
    QStringList ret;
    while(query.next())
    {
        QString tmp = query.value(0).toString();
        ret.append(tmp);
    }
    return ret;
}

int DB::handleSearchUsr(const char *name)
{
    QString data=QString("select onlint from userInfo where name = \'%1\'").arg(name);
    qDebug()<<data;
    QSqlQuery query;
    query.exec(data);
    int ret = -1;
    while(query.next())
    {
        ret = query.value(0).toInt();
    }
    return ret;
}










